package com.elder.system.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.validation.Validator;

import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.MemberInfo;
import com.elder.business.domain.MemberLeaveRecord;
import com.elder.business.mapper.MemberInfoMapper;
import com.elder.business.mapper.MemberLeaveRecordMapper;
import com.elder.common.core.domain.AjaxResult;
import com.elder.common.core.domain.entity.SysDept;
import com.elder.common.core.domain.entity.SysUserDTO;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.enums.ApplyStatus;
import com.elder.common.enums.WorkState;
import com.elder.common.utils.DateUtils;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.bean.BeanUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import com.elder.system.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.elder.common.annotation.DataScope;
import com.elder.common.constant.UserConstants;
import com.elder.common.core.domain.entity.SysRole;
import com.elder.common.core.domain.entity.SysUser;
import com.elder.common.exception.ServiceException;
import com.elder.common.utils.SecurityUtils;
import com.elder.common.utils.StringUtils;
import com.elder.common.utils.bean.BeanValidators;
import com.elder.common.utils.spring.SpringUtils;
import com.elder.system.domain.SysPost;
import com.elder.system.domain.SysUserPost;
import com.elder.system.domain.SysUserRole;
import com.elder.system.service.ISysConfigService;
import com.elder.system.service.ISysUserService;

/**
 * 用户 业务层处理
 * 
 * @author zhuyongkang
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    @Autowired
    private MemberInfoMapper memberInfoMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private MemberLeaveRecordMapper memberLeaveRecordMapper;

    /**
     * 根据条件分页查询用户列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUserDTO> selectUserList(SysUser user)
    {
        List<SysUser> sysUsers = userMapper.selectUserList(user);
        List<SysUserDTO> dtoList = sysUsers.stream().map(v -> {
            SysUserDTO dto = new SysUserDTO();
            BeanUtils.copyProperties(v, dto);
            dto.setUserId(StringNewUtils.formatStr(v.getUserId()));
            dto.setDeptId(StringNewUtils.formatStr(v.getDeptId()));
            return dto;
        }).collect(Collectors.toList());
        return dtoList;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user)
    {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user)
    {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUserDTO selectUserById(Long userId)
    {
        SysUser sysUser = userMapper.selectUserById(userId);
        SysUserDTO dto = new SysUserDTO();
        BeanUtils.copyProperties(sysUser, dto);
        dto.setUserId(StringNewUtils.formatStr(sysUser.getUserId()));
        dto.setDeptId(StringNewUtils.formatStr(sysUser.getDeptId()));
        return dto;
    }

    /**
     * 查询用户所属角色组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName)
    {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     * 
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     * 
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUserDTO> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        user.setUserId(SnowGenerator.getId());
        int rows = userMapper.insertUser(user);
        //向添加成员信息
        MemberInfo memberInfo = new MemberInfo();
        memberInfo.setMemberId(SnowGenerator.getId());
        memberInfo.setUserId(user.getUserId());
        memberInfo.setDeptId(user.getDeptId());
        memberInfo.setSex(user.getSex());
        memberInfo.setStatus(WorkState.WORKING.getValue());
        memberInfo.setMemberName(user.getNickName());
        memberInfo.setMemberType(user.getDeptId());
        memberInfoMapper.insertMemberInfo(memberInfo);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user)
    {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds)
    {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     * 
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar)
    {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     * 
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     * 
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     * 
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     * 
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds)
    {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /***
     * @description 用户忘记密码重置
     * @param user
     * @return AjaxResult
     * @author zyk
     * @date 2024/2/29 14:39
     */
    @Override
    public AjaxResult ForgotPassword(SysUser user) {
        SysUser userInfo = userMapper.getUserInfo(user.getPhonenumber(), user.getEmail());
        if(Objects.isNull(userInfo)){
            throw new ServiceException("该用户不存在，请联系管理员添加");
        }
        userInfo.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        // 更新用户信息（重置密码）
        userMapper.updateUser(userInfo);
        return AjaxResult.success();
    }

    @Override
    public JSONObject getOneMember(Long userId) {
        MemberInfo member = memberInfoMapper.getMember(userId);
        SysDept sysDept = deptMapper.selectDeptById(member.getMemberType());
        JSONObject obj = new JSONObject();
        if(Objects.nonNull(member)){
            obj.put("memberId",StringNewUtils.long2Str(member.getMemberId()));
            obj.put("memberName",member.getMemberName());
            obj.put("deptId",member.getDeptId());
            obj.put("deptName",Objects.isNull(sysDept)?"":sysDept.getDeptName());
            obj.put("age",member.getAge());
            obj.put("sex",member.getSex());
            obj.put("edu",member.getEdu());
            obj.put("school",member.getSchool());
            obj.put("height",member.getHeight());
            obj.put("status",WorkState.getCnName(member.getStatus()));
            obj.put("brief",member.getBrief());
            return obj;
        }
        return obj;
    }

    @Override
    public TableDataInfo getLeaveApprovalList(String status,Integer pageNum,Integer pageSize) {
        Integer applyStatus = null;
        if(status != null){
            applyStatus = ApplyStatus.getValue(status);
        }
//        //时间处理
//        Long daystartTime = null;
//        Long dayendTime = null;
//        if(!StringNewUtils.isEmpty(startTime)&& !StringNewUtils.isEmpty(endTime)){
//            Long currentTime = DateUtils.getTargetDateSeconds(startTime);
//            Long endCurrentTime = DateUtils.getTargetDateSeconds(endTime);
//            daystartTime = DateUtils.getDayStartTime(currentTime);
//            dayendTime = DateUtils.getDayEndTime(endCurrentTime);
//        }
//        List<Long> memberIds = StringNewUtils.isEmpty(memberName)?null:memberInfoMapper.getMemberListByMemberName(memberName);
        //分页
        PageHelper.startPage(pageNum, pageSize);
        List<MemberLeaveRecord> list = memberLeaveRecordMapper.getMemberLeaveRecordList(null,applyStatus,null,null);
        PageInfo<MemberLeaveRecord> pageInfo = new PageInfo<>(list);
        List<MemberLeaveRecord> memberLeaveRecordList = pageInfo.getList();
        List<Long> memberIdList = memberLeaveRecordList.stream().map(MemberLeaveRecord::getMemberId).collect(Collectors.toList());
        Map<Long,MemberInfo> memberMap = CollectionUtils.isEmpty(memberIdList)?new HashMap<>():(memberInfoMapper.getMemberDept(memberIdList)
                .stream().collect(Collectors.toMap(MemberInfo::getMemberId, Function.identity())));

        List<JSONObject> objectList = memberLeaveRecordList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("leaveId", StringNewUtils.formatStr(v.getLeaveId()));
            obj.put("memberId", StringNewUtils.formatStr(v.getMemberId()));
            if(Objects.isNull(memberMap.get(v.getMemberId()))){
                obj.put("deptId","");
                obj.put("deptName","");
                obj.put("memberName", "");
            }else {
                obj.put("deptId", memberMap.get(v.getMemberId()).getDeptId());
                obj.put("deptName", memberMap.get(v.getMemberId()).getDeptName());
                obj.put("memberName", memberMap.get(v.getMemberId()).getMemberName());
            }
            obj.put("title", v.getTitle());
            obj.put("reason", v.getReason());
            obj.put("leaveTime", DateUtils.dateStrMIAO(v.getLeaveTime()));
            obj.put("backTime", DateUtils.dateStrMIAO(v.getBackTime()));
            obj.put("state", ApplyStatus.getCnName(v.getState()));
            obj.put("notes", v.getNotes());
            return obj;
        }).collect(Collectors.toList());
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(200);
        dataInfo.setTotal(pageInfo.getTotal());
        dataInfo.setRows(objectList);
        return dataInfo;
    }
}
